import { ElLoading, ElMessage } from 'element-plus'
import axios from 'axios'
let loadingCount = 0
let loadings = ''

function getAxios(settings, timeout = 10000 * 6) {
  const ins = axios.create(settings)
  ins.defaults.timeout = timeout
  ins.defaults.method = 'GET'
  ins.defaults.headers.post['Content-Type'] = 'application/json;charset=utf-8'
  ins.defaults.headers.put['Content-Type'] = 'application/json;charset=utf-8'
  setInterceptors(ins, settings.loading, settings.limit, settings.showError, settings.loadBody)
  return ins
}

function setInterceptors(
  axiosIns,
  loading = true,
  limit = true,
  showError = true,
  loadBody = true,
) {
  axiosIns.interceptors.request.use(
    (req) => {
      // 是否开启 loading
      if (loading) {
        loadingCount++
        loadings = ElLoading.service({
          lock: true,
          text: 'Loading',
          background: 'rgba(0, 0, 0, 0.7)',
          /* target: loadBody ? document.body : document.querySelector('.loading-area'), */
        })
      }
      return req
    },
    (error) => {
      return Promise.reject(error)
    },
  )
  axiosIns.interceptors.response.use(
    (res, req) => {
      if (loading) {
        loadingCount--
        loadingCount <= 0 && loadings.close && loadings.close()
      }
      // //未登录
      if (res.data.errorCode == '401' || res.data.code == '401') {
        window.location.href = res.data.redirect_url
        return Promise.reject(false)
      }

      // 没有权限
      if (res.data.errorCode == '403' || res.data.code == '403') {
        ElMessage({
          message: '您没有此操作权限，请联系管理员开通。',
          type: 'error',
          duration: 2000,
        })
        return Promise.reject(res.data)
      }

      if (
        res.config.responseType === 'blob' ||
        res.config.responseType === 'arraybuffer' ||
        res.config.url.includes('json')
      ) {
        return res
      }

      if (res.config.url.indexOf('/sso') != -1 && res.data.errorCode == 0) {
        return res.data
      }

      if (
        (res.data && res.data.code && res.data.code == 1) ||
        (res.data.statusCode && res.data.statusCode == 200)
      ) {
        // 兼容后端暂时为了效率，都没有算count，默认返回100情况
        if (res.data.total == 100 && (res.data.results == null || res.data.results.length == 0)) {
          res.data.total = 0
        }
        return res.data
      } else {
        if (showError) {
          ElMessage({
            message: res.data.message || res.data.msg,
            type: 'error',
            duration: 5000,
          })
        }
        return Promise.reject(res.data)
      }
    },
    (error) => {
      if (loading) {
        loadingCount--
        loadingCount <= 0 && loadings.close && loadings.close()
      }
      ElMessage({
        message: error.message || error.msg,
        type: 'error',
        duration: 5000,
      })
      return Promise.reject(error)
    },
  )
}

export default getAxios
